package com.appbee.cm.client.nav.ui;

import javax.inject.Inject;
import javax.inject.Singleton;

import com.appbee.cm.client.nav.presenter.NavStyleRegistry;
import com.appbee.cm.client.nav.presenter.SimpleNavStyleWrap;
import com.appbee.core.client.json.Json;
import com.appbee.core.client.modular.SettingsView;
import com.google.gwt.core.client.GWT;
import com.google.gwt.json.client.JSONObject;
import com.google.gwt.json.client.JSONString;
import com.google.gwt.text.shared.AbstractRenderer;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.ValueListBox;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.view.client.ProvidesKey;

@Singleton
public class NavSettingsView extends Composite implements SettingsView
{

	private static NavSettingsViewUiBinder uiBinder = GWT
			.create(NavSettingsViewUiBinder.class);

	interface NavSettingsViewUiBinder extends UiBinder<Widget, NavSettingsView>
	{
	}

	@UiField(provided = true)
	NavSelectionBox parentId;

	@UiField(provided = true)
	ValueListBox<SimpleNavStyleWrap> navStyle = new ValueListBox<SimpleNavStyleWrap>(
			new Render(), new ProvidesKey<SimpleNavStyleWrap>()
			{

				@Override
				public Object getKey(SimpleNavStyleWrap item)
				{
					return item == null ? null : item.getId();
				}

			});

	private final NavStyleRegistry navStyleRegistry;

	@Inject
	public NavSettingsView(	NavStyleRegistry navStyleRegistry,
							NavSelectionBox navSelectionBox)
	{
		this.navStyleRegistry = navStyleRegistry;
		parentId = navSelectionBox;
		navStyle.setAcceptableValues(navStyleRegistry.getSimpleNavStyles());
		initWidget(uiBinder.createAndBindUi(this));
	}

	@Override
	public void setSettingsString(String value)
	{
		Json json = Json.parseStrict(value);
		Long parentLongId = json.getStringAsLong("parentId", null);
		parentId.setNavId(parentLongId);
		SimpleNavStyleWrap style = navStyleRegistry.getById(json
				.getString("style", null));
		navStyle.setValue(style);
	}

	@Override
	public String toSettingsString()
	{
		JSONObject json = new JSONObject();
		if (parentId.getValue() != null)
		{
			json.put(	"parentId",
						new JSONString(String.valueOf(parentId.getValue()
								.getWrappedItem().getId())));
		}
		if (navStyle.getValue() != null)
			json.put("style", new JSONString(navStyle.getValue().getId()));
		return json.toString();
	}

	private class Render extends AbstractRenderer<SimpleNavStyleWrap>
	{

		@Override
		public String render(SimpleNavStyleWrap object)
		{
			return object == null ? "" : object.getName();
		}

	}

}
